
import { ModelModeType } from '@/services/types/app';
import { dsFind, dsFindOne, dsInsert, dsUpdateById, dsUpdateByKeys, ComparsionOperator } from '..';
import { FORM_SCHEMA_CLASS_IDENTIFIER, FORM_SCHEMA_ITEM_CLASS_IDENTIFIER, MODEL_CLASS_IDENTIFIER, MODEL_PROVIDER_CLASS_IDENTIFIER, MODEL_PROVIDER_SETTING_CLASS_IDENTIFIER, MODEL_TYPE_SETTING_CLASS_IDENTIFIER } from '../../constants';
import { ModelTypeEnum } from '@/components/header/account-setting/model-provider-page/declarations';


export interface ModelProvider {

}

export interface Model {

}
//获取所有的model provider
export const modelGetProviders = async (): Promise<Array<ModelProvider>> => {
    try {
        let schemaItemExtension: any = {
            "credential_form_schemas": [
                FORM_SCHEMA_ITEM_CLASS_IDENTIFIER,
                {
                    relations: [
                        {
                            conditions: {
                                related_at: 'schema_identifier'
                            }
                        }
                    ]
                }
                , { class_selector: {} }
            ]
        };

        let response = await dsFind(0, MODEL_PROVIDER_CLASS_IDENTIFIER,
            {},
            {
                class_selector: {
                    "settings": [
                        MODEL_PROVIDER_SETTING_CLASS_IDENTIFIER,
                        {
                            relations: [
                                {
                                    conditions: {
                                        related_at: 'provider_identifier'
                                    }
                                }
                            ]
                        }
                        , { class_selector: {} }
                    ],
                    "provider_credential_schema": [
                        FORM_SCHEMA_CLASS_IDENTIFIER,
                        {
                            relations: [
                                {
                                    conditions: {
                                        related_at: 'provider_form_schema'
                                    }
                                }
                            ]
                        }
                        , { class_selector: schemaItemExtension }
                    ],
                    "model_credential_schema": [
                        FORM_SCHEMA_CLASS_IDENTIFIER,
                        {
                            relations: [
                                {
                                    conditions: {
                                        related_at: 'model_form_schema'
                                    }
                                }
                            ]
                        }
                        , { class_selector: schemaItemExtension }
                    ]
                }
            },
        );

        console.log(response);

        const { data, total } = response;
        console.log('[modelGetProviders]', data);

        return data.map((item, index) => {

            let custom_configuration = item.is_active === 1 || (item.settings && item.settings.length > 0) ? {
                "status": "active"
            } : {
                "status": "unactive"
            };

            return {
                id: item.id,
                identifier: item.identifier,
                name: item.name,
                provider: item.name,
                title: item.title,
                icon: item.icon,
                description: item.description,
                background: item.colors ? JSON.parse(item.colors).background : undefined,
                "custom_configuration": custom_configuration,
                "configurate_methods": [
                    "predefined-model"
                ],
                "supported_model_types": item.supported_model_types ? item.supported_model_types.split(',') : [],
                "system_configuration": {
                    "enabled": false,
                    "current_quota_type": null,
                    "quota_configurations": []
                },
                "provider_credential_schema": item.provider_credential_schema[0],
                "model_credential_schema": item.model_credential_schema[0],
                "preferred_provider_type": "custom",
            };
        });
    } catch (err) {
        console.error(err);
    }
    return [];
}


export const modelGetProviderModels = async (provider_identifier: string): Promise<Array<Model>> => {
    try {
        let response = await dsFind(0, MODEL_CLASS_IDENTIFIER,
            {
                attributes: [
                    {
                        name: 'provider_identifier',
                        operator: ComparsionOperator.Equal,
                        value: provider_identifier
                    }
                ]
            },
            {
                class_selector: {
                }
            },
        );

        // console.log(response);

        const { data, total } = response;
        console.log('[modelGetProviderModels]', data);

        return data.map((item, index) => {

            // let custom_configuration = item.settings && item.settings.length > 0 ? {
            //     "status": "active"
            // } : {
            //     "status": "unactive"
            // };
            return {
                id: item.id,
                identifier: item.identifier,
                name: item.name,
                provider: item.name,
                title: item.title,
                icon: item.icon,
                description: item.description,
                "model": item.name,
                "label": {
                    "zh_Hans": item.title || item.name,
                    "en_US": item.title || item.name,
                },
                "model_type": item.model_type,
                "features": item.features ? item.features.split(',') : [],
                "fetch_from": "predefined-model",
                "model_properties": {
                    "mode": "chat",
                    "context_size": 128000
                },
                "deprecated": item.deprecated,
                "status": "active",
                "load_balancing_enabled": false,
            };
        });
    } catch (err) {
        console.error(err);
    }
    return [];
}

export const modelGetMode = (model_type: ModelTypeEnum): ModelModeType => {
    if (model_type === ModelTypeEnum.tts) {
        return ModelModeType.tts;
        return
    }
    return ModelModeType.chat;
}

//通过类型进行模型的查询
export const modelGetProviderAndModelsByType = async (modelType: string): Promise<Array<Model>> => {
    try {
        let response = await dsFind(0, MODEL_PROVIDER_CLASS_IDENTIFIER,
            {
            },
            {
                class_selector: {
                    "models": [
                        MODEL_CLASS_IDENTIFIER,
                        {
                            attributes: [{
                                name: 'model_type',
                                operator: ComparsionOperator.Equal,
                                value: modelType
                            }],
                            relations: [
                                {
                                    conditions: {
                                        related_at: 'provider_identifier'
                                    }
                                }
                            ]
                        }
                        , { class_selector: {} }
                    ],
                }
            },
        );

        // console.log(response);
        const { data, total } = response;

        return data.map((item, index) => {

            return {
                id: item.id,
                identifier: item.identifier,
                name: item.name,
                provider: item.name,
                title: item.title,
                icon: item.icon,
                description: item.description,
                background: item.colors ? JSON.parse(item.colors).background : undefined,
                "label": {
                    "zh_Hans": item.title || item.name,
                    "en_US": item.title || item.name,
                },
                "icon_small": {
                    "zh_Hans": "/console/api/workspaces/current/model-providers/openai/icon_small/zh_Hans",
                    "en_US": "/console/api/workspaces/current/model-providers/openai/icon_small/en_US"
                },
                "icon_large": {
                    "zh_Hans": "/console/api/workspaces/current/model-providers/openai/icon_large/zh_Hans",
                    "en_US": "/console/api/workspaces/current/model-providers/openai/icon_large/en_US"
                },
                "status": "active",
                "models": item.models.map((item, index) => {
                    return {
                        "identifier": item.identifier,
                        "model": item.name,
                        "label": {
                            "zh_Hans": item.title,
                            "en_US": item.title,
                        },
                        "model_type": item.model_type,
                        "features": item.features ? item.features.split(',') : [],
                        "fetch_from": item.fetch_from,
                        "model_properties": {
                            "mode": "chat",
                            "context_size": 128000
                        },
                        "deprecated": item.deprecated,
                        "status": "active",
                        "load_balancing_enabled": false
                    };
                }),
            };
        });
    } catch (err) {
        console.error(err);
    }
    return [];
}


export const modelFetchDefaultModal = async (modelType: string): Promise<Model> => {
    try {
        console.log('-----', modelType);
        let response = await dsFindOne(0, MODEL_TYPE_SETTING_CLASS_IDENTIFIER,
            {
                attributes: [
                    {
                        name: 'model_type',
                        operator: ComparsionOperator.Equal,
                        value: modelType
                    }
                ]
            },
            {
                class_selector: {
                    "providers": [
                        MODEL_PROVIDER_CLASS_IDENTIFIER,
                        {
                            relations: [
                                {
                                    conditions: {
                                        related_at: 'default_provider'
                                    }
                                }
                            ]
                        }
                        , { class_selector: {} }
                    ],
                }
            },
        );
        console.log(response);
        if (response) {
            return {
                "model": response.default_model,
                "model_type": modelType,
                "provider": {
                    "provider": response.default_provider,
                    "label": {
                        "zh_Hans": response.default_provider,
                        "en_US": response.default_provider
                    },
                    "icon_small": {
                        "zh_Hans": "/console/api/workspaces/current/model-providers/openai/icon_small/zh_Hans",
                        "en_US": "/console/api/workspaces/current/model-providers/openai/icon_small/en_US"
                    },
                    "icon_large": {
                        "zh_Hans": "/console/api/workspaces/current/model-providers/openai/icon_large/zh_Hans",
                        "en_US": "/console/api/workspaces/current/model-providers/openai/icon_large/en_US"
                    },
                    "supported_model_types": [
                        "llm",
                        "text-embedding",
                        "speech2text",
                        "moderation",
                        "tts"
                    ],
                    "models": []
                }
            };
        } else {
            return null;
        }
    } catch (err) {
        console.error(err);
    }
    return null;
}

export const modelUpdateDefaultModel = async (typeSettings: Array<{ model_type: string, provider: string, model: string }>): Promise<boolean> => {

    //
    for (let i = 0; i < typeSettings.length; i++) {
        let typeSetting = typeSettings[i];

        let _ = await dsUpdateByKeys(0, MODEL_TYPE_SETTING_CLASS_IDENTIFIER, [typeSetting.model_type], {
            model_type: typeSetting.model_type,
            default_model: typeSetting.model,
        }, {
            upsert: true,
            primary_key: 'model_type'
        });
    }
    return true;
}

export const modelSaveProviderCredentials = async (provider: any, v: Record<string, any>): Promise<any> => {
    // dsInsert();
    let res = await dsUpdateByKeys(0, MODEL_PROVIDER_SETTING_CLASS_IDENTIFIER, [provider.identifier], {
        provider_identifier: provider.identifier,
        encrypted_config: JSON.stringify(v)
    }, {
        upsert: true,
        primary_key: 'provider_identifier'
    });
    return res;
}


export const modelFetchModelProviderCredentials = async (provider: any): Promise<{
    credentials?: Record<string, string | undefined | boolean>
    load_balancing?: any
}> => {
    // dsInsert();
    let data = await dsFindOne(0, MODEL_PROVIDER_SETTING_CLASS_IDENTIFIER, {
        attributes: [{
            name: 'provider_identifier',
            operator: ComparsionOperator.Equal,
            value: provider
        }]
    });

    return {
        credentials: JSON.parse(data.encrypted_config)
    };
}

// TODO
// fetchModelParameterRules